﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Common;
using ImageProcesser.Properties;

namespace ImageProcesser
{
    public partial class ImageProcessorForm : Form
    {
        private ImageProcessApp app;
        private EventHandler zoomFactorTrackValueChangedHandler;
        //图像路径集合
        List<string> ImgLsts = new List<string>();
        int jpgPageindex = 0;
        

        class FormMenuRegistry : IMenuRegistry
        {
            private MenuStrip menu;
            ImageProcessApp app;
            public FormMenuRegistry(MenuStrip m, ImageProcessApp ipapp)
            {
                menu = m;
                app = ipapp;
            }

            class MenuTag
            {
                public string MenuID;
                public IProcessorPlugin Plugin;
            }

            #region IMenuRegistry Members

            public void RegisterMenuItem(string ParentMenuString, string MenuString, string MenuID, Keys shortCut, IProcessorPlugin plugin)
            {
                ToolStripMenuItem parent = null;
                foreach (ToolStripItem item in menu.Items)
                {
                    if (item.Text == ParentMenuString)
                    {
                        parent = (ToolStripMenuItem)item;
                        break;
                    }
                }
                if (parent == null)
                {
                    parent = new ToolStripMenuItem(ParentMenuString);
                    parent.DropDownOpening += new EventHandler(DropDownOpening);
                    parent.DropDownClosed += new EventHandler(DropDownClosed);
                    menu.Items.Insert(menu.Items.Count - 1, parent);
                }

                ToolStripMenuItem itemAdded = new ToolStripMenuItem(MenuString);
                MenuTag tag = new MenuTag();
                tag.MenuID = MenuID;
                tag.Plugin = plugin;
                itemAdded.Tag = tag;
                itemAdded.ShortcutKeys = shortCut;
                parent.DropDownItems.Add(itemAdded);
                itemAdded.Click += new EventHandler(itemAdded_Click);
            }

            void DropDownClosed(object sender, EventArgs e)
            {
                ToolStripMenuItem item = (ToolStripMenuItem)sender;
                for (int i = 0; i < item.DropDownItems.Count; i++)
                {
                    item.DropDownItems[i].Enabled = true;
                }
            }


            void DropDownOpening(object sender, EventArgs e)
            {
                ToolStripMenuItem item = (ToolStripMenuItem)sender;
                for (int i = 0; i < item.DropDownItems.Count; i++)
                {
                    item.DropDownItems[i].Enabled = app.CurrentDoc != null;
                }
            }

            void itemAdded_Click(object sender, EventArgs e)
            {
                if (app.CurrentDoc != null)
                {
                    ToolStripMenuItem item = (ToolStripMenuItem)sender;
                    MenuTag tag = (MenuTag)item.Tag;
                    tag.Plugin.ProcessCommand(tag.MenuID, app.CurrentDoc);
                }
            }

            #endregion
        }

        public ImageProcessorForm()
        {
            InitializeComponent();
            AppInstance.Initialize();
            app = AppInstance.GetApplication();
        }

        void zoomFactorTrackBar_ValueChanged(object sender, EventArgs e)
        {
            if (app.ImageView != null)
            {
                app.ImageView.ZoomFactor = zoomFactorTrackBar.Value;
            }
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                OpenFile(openFileDialog.FileName);
                Program.CommandLineFileName = openFileDialog.FileName;
            }
        }

        private void OpenFile(string fileName)
        {
            try
            {
                app.CurrentDoc = new Document(fileName);
                app.CurrentDoc.SetMaxUndoCount(5);
                InitView();
            }
            catch (Exception)
            {
                MessageBox.Show("Cannot open file \"" + fileName + "\".", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void InitView()
        {
            if (app.ImageView != null)
                app.ImageView.Dispose();
            app.ImageView = new Common.View(app.CurrentDoc);
            app.ImageView.ZoomFactorChanged += new Common.View.ZoomFactorChangedEvent(ImageView_ZoomFactorChanged);
            app.ImageView.Parent = docPanel;
            app.ImageView.Dock = DockStyle.Fill;
            app.ImageView.ViewMode = ViewMode.BestFit;
            app.ImageView.Cursor = new Cursor(GetType(), "curDown.cur");
        }

        void ImageView_ZoomFactorChanged(int zoom, float rate)
        {
            zoomFactorTrackBar.ValueChanged -= zoomFactorTrackValueChangedHandler;
            if (zoom < zoomFactorTrackBar.Minimum) zoom = zoomFactorTrackBar.Minimum;
            if (zoom > zoomFactorTrackBar.Maximum) zoom = zoomFactorTrackBar.Maximum;
            zoomFactorTrackBar.Value = zoom;
            zoomFactorTrackBar.ValueChanged += zoomFactorTrackValueChangedHandler;
            zoomRateLabel.Text = (rate * 100).ToString("F0") + "%";
        }

        private void bestFitButton_Click(object sender, EventArgs e)
        {
            if (app.ImageView != null)
                app.ImageView.ViewMode = ViewMode.BestFit;
        }

        private void originalSizeButton_Click(object sender, EventArgs e)
        {
            if (app.ImageView != null)
                app.ImageView.ViewMode = ViewMode.OriginalSize;
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new AboutBox().ShowDialog();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (app.CurrentDoc != null)
            {
                if (Program.CommandLineFileName != "")
                {
                    try
                    {
                        System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Jpeg;
                        app.CurrentDoc.GetBitmap().Save(@Program.CommandLineFileName, format);
                        MessageBox.Show("保存成功.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("保存失败.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }
        }

        private void undoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (app.CurrentDoc != null)
            {
                app.CurrentDoc.Undo();
                app.ImageView.ViewMode = app.ImageView.ViewMode;
            }
        }

        private void redoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (app.CurrentDoc != null)
            {
                app.CurrentDoc.Redo();
                app.ImageView.ViewMode = app.ImageView.ViewMode;
            }
        }

        private void editMenu_DropDownOpening(object sender, EventArgs e)
        {
            redoToolStripMenuItem.Enabled = app.CurrentDoc != null && app.CurrentDoc.CanRedo();
            undoToolStripMenuItem.Enabled = app.CurrentDoc != null && app.CurrentDoc.CanUndo();
        }

        private void filterToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
        {
            ToolStripMenuItem item = (ToolStripMenuItem)sender;
            for (int i = 0; i < item.DropDownItems.Count; i++)
            {
                item.DropDownItems[i].Enabled = app.CurrentDoc != null;
            }
        }

        private void editMenu_DropDownClosed(object sender, EventArgs e)
        {
            redoToolStripMenuItem.Enabled = true;
            undoToolStripMenuItem.Enabled = true;

        }

        private void transformToolStripMenuItem_DropDownClosed(object sender, EventArgs e)
        {
            ToolStripMenuItem item = (ToolStripMenuItem)sender;
            for (int i = 0; i < item.DropDownItems.Count; i++)
            {
                item.DropDownItems[i].Enabled = true;
            }
        }

        private void docPanel_DragOver(object sender, DragEventArgs e)
        {

        }

        private void docPanel_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Link;
            else e.Effect = DragDropEffects.None;

        }

        private void docPanel_DragDrop(object sender, DragEventArgs e)
        {
            OpenFile(((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString());
        }
        //应用程序执行路径
        public static string APPdirPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);

        private void ImageProcessorForm_Load(object sender, EventArgs e)
        {
            this.Text += "—[" + Program.CurHtmc + "]";
            zoomFactorTrackValueChangedHandler = new EventHandler(zoomFactorTrackBar_ValueChanged);
            zoomFactorTrackBar.ValueChanged += zoomFactorTrackValueChangedHandler;
            if (AppInstance.GetPlugins() != null)
            {
                foreach (IProcessorPlugin plugin in AppInstance.GetPlugins())
                {
                    plugin.RegisterMenu(new FormMenuRegistry(mainMenu, app));
                }
            }
            if (Program.CommandLineFileName != "")
                OpenFile(Program.CommandLineFileName);

            PeerPublicLib.SqliteVbNetHelper.CreateIns();
            string sqlstr = "select path,filename from multi_media_info where media_type=1 and study_no=" + Program.CurHtID + " order by timestamp asc";
            DataTable dt = PeerPublicLib.SqliteVbNetHelper.SqliteDB.GetDataTable(sqlstr);
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ImgLsts.Add(string.Format(@"{0}{1}\{2}", APPdirPath, dt.Rows[i]["path"].ToString(), dt.Rows[i]["filename"].ToString()));
                }
            }
            btnUp.Enabled = false;
            btnDown.Enabled = false;
            jpgPageindex = 0;
            if (ImgLsts.Count > 0)
            {
                if (ImgLsts.Count == 1)
                {
                    btnDown.Enabled = false;
                    btnUp.Enabled = false;
                }
                else
                {
                    btnUp.Enabled = false;
                    btnDown.Enabled = true;
                }
                //打开文件
                OpenFile(ImgLsts[0]);
                Program.CommandLineFileName = ImgLsts[0];
                jpgPageindex = 0;
            }
        }

        private void btnUp_Click(object sender, EventArgs e)
        {
            if (ImgLsts.Count > 0)
            {
                jpgPageindex = jpgPageindex - 1;
                if (jpgPageindex <= 0)
                {
                    jpgPageindex = 0;
                    btnUp.Enabled = false;
                    btnDown.Enabled = true;
                }
                if (jpgPageindex == ImgLsts.Count - 1)
                {
                    btnDown.Enabled = false;
                }
                if (jpgPageindex < ImgLsts.Count - 1)
                {
                    btnDown.Enabled = true;
                }
                if (jpgPageindex > 0 && jpgPageindex < ImgLsts.Count - 1)
                {
                    btnUp.Enabled = true;
                }
                OpenFile(ImgLsts[jpgPageindex]);
                Program.CommandLineFileName = ImgLsts[jpgPageindex];
            }
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            if (ImgLsts.Count > 0)
            {
                jpgPageindex = jpgPageindex + 1;
                if (jpgPageindex >= ImgLsts.Count - 1)
                {
                    jpgPageindex = ImgLsts.Count - 1;
                    btnDown.Enabled = false;
                    btnUp.Enabled = true;
                }
                if (jpgPageindex == 0)
                {
                    btnUp.Enabled = false;
                }
                if (jpgPageindex < ImgLsts.Count - 1)
                {
                    btnDown.Enabled = true;
                }
                if (jpgPageindex > 0 && jpgPageindex < ImgLsts.Count - 1)
                {
                    btnUp.Enabled = true;
                }
                OpenFile(ImgLsts[jpgPageindex]);
                Program.CommandLineFileName = ImgLsts[jpgPageindex];
            }
        }
    }
}
